package com.jdk.parallerutils.semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description :一个计数信号量。 通常用于限制可以访问某些资源（物理或逻辑的）的线程数目。
 * @FileName: SemaphoreTest.java
 * @Author :WeiHui.Zhang
 * @Data : 2015年11月23日 下午3:49:02
 * @Version:V1.00
 */
public class SemaphoreTest {

	private final static Logger LOGGER = LoggerFactory.getLogger(SemaphoreTest.class);

	public static void main(String... args) {

		LOGGER.info("hello{}", 12);

		ExecutorService exec = Executors.newCachedThreadPool();
		final Semaphore semp = new Semaphore(3);
		for (int index = 0; index < 5; index++) {
			final int NO = index;
			Runnable run = new Runnable() {
				public void run() {
					try {
						// 获取许可
						semp.acquire();

						System.out.println("Accessing: " + Thread.currentThread().getName() + "--" + NO);
						Thread.sleep(2000);
						// 访问完后，释放
						semp.release();
						System.out.println("-----------------" + semp.availablePermits());
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			};
			exec.execute(run);

		}
		exec.shutdown();
	}
}
